package se.perp.c4.model;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import static se.perp.c4.model.Actor.EActor.*;
import se.perp.c4.model.Actor.Side;

public class ActorCollection implements Serializable, Iterable<Actor> {

    private Map<Actor.EActor, Actor> actors = new HashMap<Actor.EActor, Actor>();

    public ActorCollection() {
        actors.put(FRODO, ActorFactory.create(FRODO));
        actors.put(SAM, ActorFactory.create(SAM));
        actors.put(MERRY, ActorFactory.create(MERRY));
        actors.put(PIPPIN, ActorFactory.create(PIPPIN));
        actors.put(GIMLI, ActorFactory.create(GIMLI));
        actors.put(LEGOLAS, ActorFactory.create(LEGOLAS));
        actors.put(ARAGORN, ActorFactory.create(ARAGORN));
        actors.put(BOROMIR, ActorFactory.create(BOROMIR));
        actors.put(GANDALF, ActorFactory.create(GANDALF));
        actors.put(FRODO, ActorFactory.create(FRODO));

        actors.put(CAVETROLL, ActorFactory.create(CAVETROLL));
        actors.put(WARG, ActorFactory.create(WARG));
        actors.put(SHELOB, ActorFactory.create(SHELOB));
        actors.put(BALROG, ActorFactory.create(BALROG));
        actors.put(B_RIDERS, ActorFactory.create(B_RIDERS));
        actors.put(F_NAZGUL, ActorFactory.create(F_NAZGUL));
        actors.put(SARUMAN, ActorFactory.create(SARUMAN));
        actors.put(WITCHKING, ActorFactory.create(WITCHKING));
        actors.put(ORCS, ActorFactory.create(ORCS));
    }

    public int countLiving(Side whoWon) {
        int ret = 0;
        for (Actor a : actors.values()) {
            if (a.side == whoWon && a.isAlive) {
                ret++;
            }
        }
        return ret;
    }

    public Actor get(Actor.EActor id) {
        return actors.get(id);
    }

    public void setAllAsUnplaced() {
        for (Actor a : actors.values()) {
            a.where = Territory.ETerritory.NOWHERE;
        }
    }

    public void setAllAsLiving() {
        for (Actor a : actors.values()) {
            a.isAlive = true;
        }
    }

    public Iterator<Actor> iterator() {
        return actors.values().iterator();
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        for (Actor a : actors.values()) {
            sb.append(a.toString() +"\n");
        }
        return sb.toString();
    }

}
